package ca.etsmtl.gti785.util;

import java.util.ArrayList;
import com.google.gson.Gson;
import ca.etsmtl.gti785.classes.Application;
import ca.etsmtl.gti785.classes.Server;
import android.content.Context;
import android.content.SharedPreferences;

/**
 * This class is used to keep tracks of the servers infos between sessions of the application.
 * @author Étienne Faucher
 */
public class AppSavedSettings {

	private static SharedPreferences _sharedPref;
	
	public AppSavedSettings(Context context)
	{
		 _sharedPref = context.getSharedPreferences(Constants.App_Settings_Servers_List_Name, 0);
	}
	
	public void Save()
	{
		SharedPreferences.Editor editor = _sharedPref.edit();
		SavedServerList list = new SavedServerList(Application.getInstanceOf().getServers());
		editor.putString("servers", list.toJSON());
		editor.commit();
	}
	
	public void Load()
	{
		String servers = _sharedPref.getString("servers", null);
		if(servers != null)
		{
            Gson gson = new Gson();
			SavedServerList list = gson.fromJson(servers, SavedServerList.class);
			if(list != null)
			{
				for(String item: list.getServers())
				{
					Server server = new Server(item);
					Application.getInstanceOf().AddServer(server);
				}
			}
		}
	}
	
	private class SavedServerList
	{
		private ArrayList<String> _servers;
		public SavedServerList(ArrayList<Server> servers)
		{
			_servers = new ArrayList<String>();
			for(Server item: servers)
			{
				_servers.add(item.getURL());
			}
		}
		
		public ArrayList<String> getServers()
		{
			return _servers;
		}
		
		public String toJSON()
		{
			Gson gson = new Gson();
			return gson.toJson(this);
		}
	}
}


